package com.zcf.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pagehelper.PageHelper;
import com.zcf.common.json.Body;
import com.zcf.common.result.PageResult;
import com.zcf.common.result.ResultVo;
import com.zcf.mapper.RidingOrderMapper;
import com.zcf.mappers.Demo;
import com.zcf.pojo.*;
import com.zcf.service.RidingOrderService;
import com.zcf.utils.*;
import com.zcf.vo.in.PageVo;
import com.zcf.vo.in.PersonageInviteController;
import com.zcf.vo.out.AMapUtils;
import com.zcf.vo.out.LngLat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zhouzhuang
 * @since 2018-11-28
 */
@Controller
@RequestMapping("/ridingOrder")
@CrossOrigin
@ResponseBody
public class RidingOrderController {
    @Autowired
    private RidingOrderService ridingOrderService;

    @Autowired
    private RidingOrderMapper ridingMapper;

    // 骑手订单列表
    @PostMapping("/myOrderList")
    public Body myOrderList(PageVo pv, String userId, int type) {
        User user = new User();
        user.setId(userId);
        user = user.selectById(userId);
        if (user != null) {
            return Body.newInstance("骑手不存在");
        }
        Riding riding = new Riding();
        EntityWrapper<Riding> ew = new EntityWrapper<>();
        ew.eq("user_id", userId);
        riding = riding.selectOne(ew);
        ResultVo rv = ridingOrderService.myOrderList(pv, riding.getId(), type);
        if (rv == null) {
            return Body.newInstance("查询失败");
        }
        return Body.newInstance(rv);
    }

    // 骑手查询订单
    // 骑手id
    @PostMapping("myOrderLists")
    public Body myOrderLists(PageVo pv, String rinId, Integer type) {
        User user = new User();
        user.setId(rinId);
        user = user.selectById();
        if (user == null) {
            return Body.newInstance("用户不存在");
        }

        Riding riding = new Riding();
        EntityWrapper<Riding> ews = new EntityWrapper<>();
        ews.eq("user_id", rinId);
        riding = riding.selectOne(ews);
        if (riding == null) {
            return Body.newInstance("骑手不存在");
        }
        RidingOrder ridingOrder = new RidingOrder();
        EntityWrapper<RidingOrder> ew = new EntityWrapper<>();
        if (type != null) {
            ew.eq("type", type);
        }
        ew.eq("riding_id", rinId);
        List<RidingOrder> list = ridingOrder.selectList(ew);
        List<RidingOrder> lisst = new ArrayList<>();
        for (RidingOrder ridingOrder2 : list) {
            ridingOrder2.setRidinName("ridinName");
            // 根据地址获取经纬度
            String longitude = "";
            String latitude = "";
            Demo demo = new Demo();
            Object s = demo.gaodeditu(ridingOrder2.getShopAddress());
            String appid = s.toString();
            String lon[] = appid.split(",");
            for (int i = 0; i < lon.length; i++) {
                String string = lon[i];
                if (i == 0) {
                    longitude = string;
                } else {
                    latitude = string;
                }
            }
            ridingOrder2.setAddress(longitude + "," + latitude);
            s = demo.gaodeditu(ridingOrder2.getProductAddress());
            appid = s.toString();
            String lon2[] = appid.split(",");
            for (int i = 0; i < lon2.length; i++) {
                String string = lon2[i];
                if (i == 0) {
                    longitude = string;
                } else {
                    latitude = string;
                }
            }
            ridingOrder2.setAddress(ridingOrder2.getAddress() + "," + longitude + "," + latitude);
            EntityWrapper<Evaluate> ewgg = new EntityWrapper<>();
            ewgg.eq("order_id", ridingOrder2.getOrderId());
            Evaluate log = new Evaluate();
            log = log.selectOne(ewgg);
            if (log != null) {
                ridingOrder2.setXingxing(log.getRidingClass() + "");
            }
            lisst.add(ridingOrder2);
        }
        if (pv.getPage() != null && pv.getPageSize() != null) {
            PageHelper.startPage(pv.getPage(), pv.getPageSize());
        }
        PageResult pr = PageResult.result(lisst);
        ResultVo rv = new ResultVo();
        rv.setList(pr.getRows());
        rv.setTotal(pr.getTotal());
        if (rv != null) {
            return Body.newInstance(rv);
        }
        return Body.BODY_500;
    }

    // 骑手拿到订单，修改状态
    @PostMapping("/ridingGet")
    public Body ridingGet(String id) {
        return ridingOrderService.ridingGet(id);
    }

    // 送达订单，修改状态
    @PostMapping("/endOrder")
    public Body endOrder(String id) {
        return ridingOrderService.endOrder(id);
    }

    public String DataFormats(String time) throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        now = df.parse(time);
        Date afterDate = new Date(now.getTime() + 2100000);
        return df.format(afterDate);
    }

    /**
     * 骑手查询订单
     *
     * @throws Exception 117.243168,34.217901
     */
    @PostMapping("queryAllRiding")
    public Body queryAllRiding(PageVo pv, String longitude, String latitude, String address, String rinId)
            throws Exception {
        Dining dining = new Dining();
        EntityWrapper<Dining> ew = new EntityWrapper<>();
        if (address != null && !address.equals("")) {
            address = address.substring(0, address.length() - 1);
            ew.like("address", address);
        }
        User user = new User();
        user.setId(rinId);
        int count = 0;
        List<Dining> list = dining.selectList(ew);
        List<Object> addlist = new ArrayList<Object>();
        int sun = 0;
        int counts = 0;

        for (Dining dining2 : list) {
            Double distance = 1.0;
            if (longitude != null && !longitude.equals("") && latitude != null && !latitude.equals("")) {
                JavaLarLng javaLarLng = new JavaLarLng();
                String lng = dining2.getLongitude();// javaLarLng.getLarLng(dining2.getAddress());
                String lat = dining2.getLatitude();// javaLarLng.getLarLngs(dining2.getAddress());
                Double lat1 = Double.parseDouble(lat);
                Double lng1 = Double.parseDouble(lng);
                double lat2 = Double.parseDouble(latitude);
                double lng2 = Double.parseDouble(longitude);

                LngLat start = new LngLat(lng1, lat1);
                LngLat end = new LngLat(lng2, lat2);
                distance = AMapUtils.calculateLineDistance(start, end);
                distance = MapUtils.GetDistance(Double.parseDouble(lat), Double.parseDouble(lng), lat2, lng2);
            }


            // 查询订单
            if (distance > 0) {//&& distance < 20000) {
                Orderinfo orderinfo = new Orderinfo();
                EntityWrapper<Orderinfo> ews = new EntityWrapper<>();
                ews.eq("din_status", "1");
                ews.eq("din_id", dining2.getId());
                List<Orderinfo> lists = orderinfo.selectList(ews);
                if (lists.size() > 0) {
                    counts = lists.size();
                    if (counts > sun) {
                        for (Orderinfo orderinfoa : lists) {
                            if (sun > counts) {
                                break;
                            }
                            RidingOrder ridingOrder = new RidingOrder();
                            EntityWrapper<RidingOrder> e = new EntityWrapper<>();
                            e.eq("order_id", orderinfoa.getOrderInfoId());
                            int cocunt = ridingOrder.selectCount(e);
                            if (cocunt > 0) {
                                continue;
                            }
                            String dateTime = this.DataFormats(orderinfoa.getAddtime());
                            orderinfoa.setTime(dateTime);
                            addlist.add(orderinfoa);
                            sun++;
                        }
                        count++;
                    }
                }
                continue;
            }
            continue;
        }
        Riding riding = new Riding();
        EntityWrapper<Riding> qwe = new EntityWrapper<>();
        qwe.eq("user_id", rinId);
        riding = riding.selectOne(qwe);
        if (addlist.size() > 0) {
            String userIds = "";
            Jisuan jisuan = new Jisuan();
            if (riding != null) {
                userIds = riding.getId();
                int totalcount = ridingMapper.countFormat(rinId);
                int dangcount = ridingMapper.countDay(rinId);
                jisuan.setZongshouru(sun);
                jisuan.setJinrishouru(dangcount);
                // 待接订单数量
                jisuan.setDaijiedanshuliang(totalcount);
            }
            jisuan.setAddlist(addlist);
            if (jisuan != null) {
                return Body.newInstance(jisuan);
            }
        }
        if (riding != null) {
            riding.setLatitude(latitude);
            riding.setLongitude(longitude);
            riding.updateById();
        }
        return Body.BODY_500;
    }

    /**
     * 查询跑腿单 orderInfoId 订单id
     */
    @PostMapping("find")
    public Body find(String orderInfoId) {

        Orderinfo orderinfo = new Orderinfo();
        orderinfo = orderinfo.selectById(orderInfoId);
        RidingOrder ridingOrder = new RidingOrder();
        EntityWrapper<RidingOrder> ew = new EntityWrapper<>();
        ew.eq("order_id", orderInfoId);
        ridingOrder = ridingOrder.selectOne(ew);
        if (ridingOrder != null) {
            Riding riding = new Riding();
            EntityWrapper<Riding> qwe = new EntityWrapper<>();
            qwe.eq("user_id", ridingOrder.getRidingId());
            riding = riding.selectOne(qwe);
            if (riding != null) {

                String address = Geocoding(riding.getLatitude(), riding.getLongitude());
                Dining dining = new Dining();
                EntityWrapper<Dining> ew2 = new EntityWrapper<>();
                ew2.eq("id", orderinfo.getDinId());
                dining = dining.selectOne(ew2);
                ridingOrder = ridingOrder.selectOne(ew);
                ridingOrder.setDinlong(dining.getLongitude());
                ridingOrder.setDinlat(dining.getLatitude());
                ridingOrder.setRemark(address);
            }
            return Body.newInstance(ridingOrder);
        } else {
            return Body.BODY_500;
        }
    }

    public String Geocoding(String latitude, String longitude) {
        String s = HttpRequest.sendGet("https://restapi.amap.com/v3/geocode/regeo", "location=" + longitude + ","
                + latitude
                + "&radius=1000&extensions=base&batch=false&roadlevel=1&sig=17851026a78538a5c0ef6fb7e39078f0&key=04fae9b07d8abd27177207d1abc8bca6");
        JSONObject jsonObject10 = JSONObject.parseObject(s).getJSONObject("regeocode")
                .getJSONObject("addressComponent");
        JSONObject jsonObject1 = JSONObject.parseObject(s).getJSONObject("regeocode").getJSONObject("addressComponent")
                .getJSONObject("streetNumber");
        String city1 = jsonObject10.getString("city");
        String province = jsonObject10.getString("province");
        String district = jsonObject10.getString("district");
        String township = jsonObject10.getString("township");
        String street = jsonObject1.getString("street");
        String address = city1 + province + district + township + street;
//		System.err.println(province);
//		System.err.println(city1);
//		System.err.println(district);
//		System.err.println(township);
//		System.err.println(street);
//		System.err.println(jsonObject10);
//		System.err.println(address);
        return address;
    }

    /**
     * 骑手来新单
     */
    @PostMapping("updateXin")
    public Body updateXin(String userId) {
        User user = new User();
        user.setId(userId);
        user = user.selectById(userId);
        if (user != null) {
            // 个推
            AppPush.pushinfoxin(user.getCid());
        }
        return Body.BODY_500;

    }
    /**
     * 骑手接单
     */
    @PostMapping("updateRidin")
    public Body updateRidin(String ridinId, String orderInfoId) {
        RidingOrder ridingOrder1 = new RidingOrder();
        EntityWrapper<RidingOrder> ew = new EntityWrapper<>();
        ew.eq("order_id", orderInfoId);
        int count = ridingOrder1.selectCount(ew);
        if (count > 0) {
            return Body.newInstance("订单已经被接");
        }
        Orderinfo orderinfo = new Orderinfo();
        orderinfo.setOrderInfoId(orderInfoId);
        orderinfo = orderinfo.selectById();
        if (orderinfo == null) {
            return Body.newInstance("订单不存在");
        }
        if (orderinfo.getDinStatus() == 0) {
            return Body.newInstance("商家未接单");
        } else if (orderinfo.getDinStatus() == 2) {
            return Body.newInstance("已经完成");
        } else if (orderinfo.getDinStatus() == 3) {
            return Body.newInstance("已拒绝");
        } else if (orderinfo.getDinStatus() == 5) {
            return Body.newInstance("骑手配送中");
        }
        Riding riding = new Riding();
        EntityWrapper<Riding> ewr = new EntityWrapper<>();
        ewr.eq("user_id", ridinId);
        riding = riding.selectOne(ewr);
        if (riding == null) {
            return Body.newInstance("骑手不存在");
        }
        if (riding.getStart_finish() == 2) {
            return Body.newInstance("您已停工，请先开工");
        }
        Dining dining = new Dining();
        dining.setId(orderinfo.getDinId());
        dining = dining.selectById();
        if (dining == null) {
            return Body.newInstance("商家不存在");
        }
        RidingOrder ridingOrder = new RidingOrder();
        ridingOrder.setId(Hutool.getId());
        ridingOrder.setGetTime(Hutool.parseDateToString());
        ridingOrder.setPhone(riding.getPhone());
        ridingOrder.setRidinName(riding.getName());
        ridingOrder.setRidingId(ridinId);
        ridingOrder.setRidinName(riding.getName());
        ridingOrder.setType(0);
        // 预计送达时间
        ridingOrder.setAppointTime(orderinfo.getPredictTime());
        ridingOrder.setProductAddress(dining.getAddress());
        ridingOrder.setProductName(dining.getDiningName());
        ridingOrder.setProductPhone(dining.getPhone());
        ridingOrder.setShopAddress(orderinfo.getAddress());
        ridingOrder.setShopName(orderinfo.getUserName());
        ridingOrder.setShopPhone(orderinfo.getPhone());
        ridingOrder.setOrderId(orderInfoId);
        Boolean flag = ridingOrder.insert();
        if (flag) {
            Orderinfo orderinfo1 = new Orderinfo();
            orderinfo1.setOrderInfoId(orderInfoId);
            orderinfo1.setStatus(1);
            orderinfo1.setDinStatus(5);
            orderinfo1.updateById();

            User user = new User();
            user.setId(orderinfo.getUserId());
            user = user.selectById();
            if (user.getCid() != "" && user.getCid() != null) {
                // 个推
                AppPush.pushinfoding(user.getCid());
            }

            return Body.newInstance(ridingOrder);
        }
        return Body.BODY_500;
    }

    /**
     * 查询骑手状态 name 骑手名字 phone 骑手手机号
     */
    @PostMapping("queryStatus")
    public Body queryStatus(String status, String phone, String name) {
        RidingOrder ridingOrder = new RidingOrder();
        EntityWrapper<RidingOrder> ew = new EntityWrapper<>();
        if (status != "" && status != null) {
            ew.eq("type", status);
        }
        if (phone != null && phone != "") {
            ew.like("phone", phone);
        }
        if (name != null && name != "") {
            ew.like("rin_name", name);
        }
        List<RidingOrder> list = ridingOrder.selectList(ew);
        List<RidingOrder> lists = new ArrayList<>();
        if (list.size() > 0) {
            for (RidingOrder ridingOrder1 : list) {
                Riding riding1 = new Riding();
                EntityWrapper<Riding> ews = new EntityWrapper<>();
                ews.eq("user_id", ridingOrder1.getRidingId());
                riding1 = riding1.selectOne(ews);
                if (riding1 == null) {
                    continue;
                }
                PersonageInviteController personageInviteController = new PersonageInviteController();
                if (riding1.getLatitude() != null && riding1.getLatitude() != "" && riding1.getLongitude() != null
                        && riding1.getLongitude() != "") {
                    System.err.println(riding1.getLatitude() + "!!!!!!!!!!!" + riding1.getLongitude());
                    String address = personageInviteController.Geocoding(riding1.getLatitude(), riding1.getLongitude());
                    ridingOrder1.setAddress(address);
                }
                ridingOrder1.setRidinName(riding1.getName());
                lists.add(ridingOrder1);
            }
            if (lists.size() > 0) {
                return Body.newInstance(lists);
            }
        }
        return Body.BODY_451;
    }

    public static void main(String[] args) throws ParseException, IOException {
        // 当前时间增加时间
//		long currentTime = System.currentTimeMillis() + 35 * 60 * 1000;
//		Date date = new Date(currentTime);
//		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//		date = df.parse("2018-12-13 13:50:12");
//		String nowTime = "";
//		nowTime = df.format(date);
//		System.out.println(nowTime);
//		// 指定时间增加时间
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//		Date now = new Date();
//		now = df.parse("2018-12-13 13:00:12");
//		System.out.println("当前时间：" + sdf.format(now));
//		Date afterDate = new Date(now.getTime() + 2100000);
//		System.out.println(sdf.format(afterDate));
//		// 或者当前时间
//		System.out.println(Hutool.parseDateToStringLp());
//		GetLatAndLngByBaidu getLatAndLngByBaidu = new GetLatAndLngByBaidu();
//		Object[] o = getLatAndLngByBaidu.getCoordinate("成都市天府四街");
//		System.out.println(o[0]);// 经度
//		System.out.println(o[1]);// 纬度
        String s = "徐州市";
        s = s.substring(0, s.length() - 1);
        System.err.println(s);
    }

}
